package com.study.happystudy.service.impl;

import com.study.happystudy.entity.ResultEntity;
import com.study.happystudy.service.SmsService;
import com.study.happystudy.tool.SmsUtil;
import com.study.happystudy.tool.VerCodeGenerateTool;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@Service
public class SmsServiceImpl implements SmsService {
    private static  final Logger logger= LoggerFactory.getLogger(SmsServiceImpl.class);
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    SmsUtil smsUtil;

    @Resource
    VerCodeGenerateTool verCodeGenerateTool;

    @Override
    public String SendSms(String phone)  {
        try{
            String code=verCodeGenerateTool.generateRandomString();
            HashMap<String, Object> templateParam = new HashMap<>();
            templateParam.put("code", code);
//            templateParam.put("code", "傻逼蓬蒿");
            smsUtil.sendSms(phone, templateParam);
            stringRedisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);//加入验证码到redis中 设置过期时间为5分钟
            return ResultEntity.Success();
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
            return ResultEntity.Fail(-1,"发送失败");
        }

    }

    @Override
    public String VerifySms(String phone, String verCode) {
        try{
            if(stringRedisTemplate.opsForValue().get(phone).equals(verCode)){
                return ResultEntity.Success(null,null,0,"登录成功");
            }else{
                return ResultEntity.Fail(-1,"验证码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
            return ResultEntity.Fail(-1,"验证失败");
        }
    }
}
